package com.zhiwang.planet.ui.my.withdraw


import android.os.Bundle
import android.os.SystemClock
import androidx.fragment.app.Fragment
import androidx.appcompat.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTRewardVideoAd
import com.zhiwang.planet.R
import com.zhiwang.planet.di.component.DaggerAccountComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.AliAccountBindEvent
import com.zhiwang.planet.event.BindPayPwdEvent
import com.zhiwang.planet.mvp.p.UserPresenter
import com.zhiwang.planet.mvp.p.WithDrawPresenter
import com.zhiwang.planet.mvp.v.UserInfoView
import com.zhiwang.planet.mvp.v.WithDrawDataView
import com.zhiwang.planet.mvp.v.WithDrawView
import com.zhiwang.planet.mvvm.model.entity.User
import com.zhiwang.planet.mvvm.model.entity.main.WithDrawBody
import com.zhiwang.planet.ui.BaseFragment
import com.zhiwang.planet.ui.RewardAdInteractionListenerAdapter
import com.zhiwang.planet.ui.RewardVideoAdListenerAdapter
import com.zhiwang.planet.ui.my.WithdrawActivity
import com.zhiwang.planet.util.Toaster
import com.zhiwang.planet.util.quickStartActivity
import com.zhiwang.planet.widget.SimpleDialogBuilder
import kotlinx.android.synthetic.main.fragment_ali_withdraw.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject


/**
 * A simple [Fragment] subclass.
 *
 */
class AliWithdrawFragment : BaseFragment(), WithDrawView, UserInfoView, WithDrawDataView, AliBindDialog.OnBindSuccessCallBack {


    private lateinit var ttAdNative: TTAdNative
    private lateinit var adVideoSlot: AdSlot
    var isBind = false

    var cashTable: List<String>? = null
    @Inject
    lateinit var withDrawPresenter: WithDrawPresenter

    @Inject
    lateinit var userPresenter: UserPresenter

    lateinit var withDrawAdapter: WithDrawAdapter

    private var hasSetPayPassword = false

    var phone: String? = null


    private val notBindClickListener = View.OnClickListener {

        if (phone == null)
            userPresenter.queryUserInfo()
        else
            AliBindDialog.create(activity!!, this, phone = phone!!).show()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerAccountComponent.builder()
                .appComponent(getAppComponent())
                .accountModule(AccountModule(context as AppCompatActivity))
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
        withDrawPresenter.withdrawView = this
        userPresenter.userInfoView = this
        userPresenter.withdrawDataView = this
        isBind = requireArguments().getBoolean("BIND")
        EventBus.getDefault().register(this)

        val width = resources.displayMetrics.widthPixels
        val height = resources.displayMetrics.heightPixels

        adVideoSlot = AdSlot.Builder()
                .setCodeId("931608653")
                .setSupportDeepLink(true)
                .setImageAcceptedSize(width, height)
                .build()
        ttAdNative = TTAdSdk.getAdManager().createAdNative(requireContext())
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_ali_withdraw, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        withDrawAdapter = WithDrawAdapter()
        recyclerView.adapter = withDrawAdapter

        withdraw_user_real_name.setOnClickListener(notBindClickListener)
        withdraw_account_name.setOnClickListener(notBindClickListener)

        addToDiposable(userPresenter.queryUserInfo())

        bindAliAccountBtn.setOnClickListener {
            quickStartActivity(BindAliAccountActivity::class.java)
        }

//        notBindLayout.visibility = if (isBind.not()) View.VISIBLE else View.GONE
//        withdrawLayout.visibility = if (isBind) View.VISIBLE else View.GONE

        confirmWithDrawBtn.setOnClickListener {
            if (cashTable == null) return@setOnClickListener
            if (isBind.not()) {
                Toaster.message("请先绑定支付宝")
                return@setOnClickListener
            }
            cash = cashTable!![withDrawAdapter.selectPos]

            if ((requireActivity() as WithdrawActivity).checkCashEnough(cash))
                playVideoAndWithDraw()
        }
        val disposable = userPresenter.getAlipayWithDrawList()
        addToDiposable(disposable)
    }


    private fun playVideoAndWithDraw() {


        ttAdNative.loadRewardVideoAd(adVideoSlot, object : RewardVideoAdListenerAdapter() {

            override fun onRewardVideoAdLoad(p0: TTRewardVideoAd?) {

                p0?.setRewardAdInteractionListener(object : RewardAdInteractionListenerAdapter() {

                    var startTime: Long = 0L

                    override fun onRewardVerify(p0: Boolean, p1: Int, p2: String?) {

                    }

                    override fun onVideoComplete() {

                    }

                    override fun onAdShow() {
                        startTime = SystemClock.elapsedRealtime()
                    }

                    override fun onAdClose() {

                        withDrawPresenter.withdrawAlipay(cash, "")
                    }

                })

                p0?.showRewardVideoAd(requireActivity())
            }

            override fun onError(p0: Int, p1: String?) {
                withDrawPresenter.withdrawAlipay(cash, "")
                p1?.apply {
                    Toaster.message(this)
                }
            }

        })
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBindAliAccount(e: AliAccountBindEvent) {
        notBindLayout.visibility = View.GONE
        withdrawLayout.visibility = View.VISIBLE
        isBind = true
        userPresenter.queryUserInfo()
        withdraw_account_name.setOnClickListener(null)
        withdraw_user_real_name.setOnClickListener(null)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBindPayPwd(e: BindPayPwdEvent) {
        hasSetPayPassword = true
    }


    var cash: String = ""


    override fun onWithDraw(body: WithDrawBody) {
        (context as WithdrawActivity).updateDiamond()

        SimpleDialogBuilder()
                .title("申请提现成功")
                .titleTextColor(R.color.colorPrimary)
                .buttonText("我知道了")
                .onButtonClick(View.OnClickListener {
                    quickStartActivity(WithDrawRecordFragment::class.java)
                })
                .content("成功申请提现${body.successNum}元，请耐心等待到账")
                .build(context!!)
                .show()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onUserInfoLoad(user: User?) {
        phone = user?.phone
        hasSetPayPassword = user!!.bindInfo.hasSetPaypassword
        if (isBind) {
            withdraw_user_real_name.text = user.bindInfo.aliRealName
            withdraw_account_name.text = user.bindInfo.aliAccountName
            withdraw_account_name.setOnClickListener(null)
            withdraw_user_real_name.setOnClickListener(null)
        } else {
            withdraw_account_name.text = "点击绑定支付宝账户"
            withdraw_user_real_name.text = "绑定账户后显示"
        }
    }

    override fun onWithDrawListLoad(data: List<String>) {
        cashTable = data
        withDrawAdapter.setDatas(cashTable!!.map { it + "元" })
    }

    override fun onBindSuccess() {
        onBindAliAccount(AliAccountBindEvent())
    }

}
